<template>
<Modal 
  :title="lang.title" v-model="drawer.show"
  :width="width"
  :closable="false"
  :mask-closable="false"
>
  <Form v-if="drawer.show" ref="_form" :labelWidth="90" :model="formData" :rules="rules">
    <Row>
      <!-- <Col :span="12">
      <FieldItem v-model="formData.name" 
        :config="{ type: 'text', clearable: true, disabled: formData.name === 'root'}"
        :formItemProps="{ label: lang.name }"/>
      </Col> -->
      <Col :span="12">
      <FieldItem v-model="formData.varName" 
        :config="{ type: 'text', clearable: true, disabled: formData.name === 'root'}"
        :formItemProps="{ label: lang.varName, prop: 'varName' }"/>
      </Col>
      <!-- <Col :span="24">
        <FormItem prop="expression" :label="lang.formula">
          <cfgCondition v-model="formData.expression" :state="sourceList.concat(variableList)" :functionTag="['sum()']"
            :logicTag="['+','-','*','/','(',')']"/>
        </FormItem>
      </Col> -->
      <Col :span="24">
      <FormItem prop="expression" :label="lang.formula">
        <textarea class="ivu-input expInput" @change="expInputChange" @blur="expInputBlur" 
          wrap="soft" autocomplete="off" spellcheck="false" rows="6"
          v-model="formData.expression" ref="expInput"></textarea>
      </FormItem>
      </Col>
      <!-- <Col :span="12">
      <FieldItem :config="{ type: 'select', options: sourceList }" v-model="formData.source"
        :formItemProps="{ label: lang.source }" @select="val => expChange('source', val.value)"/>
      </Col> -->
      <Col :span="12">
      <FieldItem :config="{ type: 'select', options: variableList }" v-model="formData.variable"
        :formItemProps="{ label: lang.variable }" @select="val => expChange('variable', val.value)"/>
      </Col>
      <Col :span="12">
      <FieldItem :config="{ type: 'text', readonly: true}" v-model="formData.value"
        :formItemProps="{ label: lang.value }"/>
      </Col>
    </Row>
    <Button class="btnValidate" @click="validate" type="primary" ghost>{{ lang.verify }}</Button>
    
    <div class="ivu-mt">
      <p v-if="calcMsg.flag" >{{ lang.verifyResult }}：
        <span style="color: blue;">{{calcMsg.content[0] || ''}}</span>
      </p>
      <div v-else>
        <p >{{ lang.verifyResult }}：<span style="color: red;">{{lang.calcFail}}</span></p>
        <p v-for="(item,index) in calcMsg.content" :key="index" style="color: red;">{{item}}</p>
      </div>
    </div>
  </Form>
  <div style="text-align: right" slot="footer">
    <Button v-if="drawer.status!=='read'" @click="drawer.show = false">{{ $t(`global.cancel`) }}</Button>
    <Button type="primary" class="ivu-ml" @click="ok"> {{$t(`global.ok`)}}</Button>
  </div>
</Modal>
</template>

<script>
export default {
  name: "routingConfigPanel",
  data(){
    return {
      currentMenu:'workCenter',
      address:[],
      expParamList: [],
      expOperatorList: ['+', '-', '*', '/', '(', ')', 'sum()'],
      formData: {
        nodeId: 0,
        name: '',
        varName: '',
        expression: '',
        value: null,
        properties: [],
        nodeType: '',
      },
      rules: {
        varName: [{ required: true, message: '编号不能为空', trigger: 'blur'}]
        // date: [{ required: true, type: 'array', message: '请输入日期', trigger: 'blur' }],
      },
      inputPosition: 0,
      calcMsg: {
        flag: true,
        content: []
      },
    }
  },
  methods:{
    async ok() {
      // this.$refs._form.validate((valid) => {
      this.$refs._form.validate(async (valid) => {
        if (valid) {
          let flag = await this.validate()
          if (!flag) { return }
          this.inputPosition = 0
          this.$emit('ok', this.formData)
          this.drawer.show = false
        }
      })
    },
    async validate() {
      let rootItem = this.hierObject.hierProperties.content.find(item => item.nodeId === this.formData.nodeId)
      let {flag, res, errContent} = await this.hierObject.calcAllExp({
        ...rootItem,
        expression: this.formData.expression
      })
      flag = !errContent.length

      this.formData.value = flag ? res : 0
      this.calcMsg = {
        flag,
        content: !flag ? errContent : [this.lang.verifySuccess]
      }
      return flag
    },
    // 公式相关
    expInputBlur() {
      this.inputPosition =  this.$refs.expInput.selectionStart
    },
    expInputChange(newCode) {
      this.calcMsg.content = []
    },
    insertText(type, val) {
      let expression = this.formData.expression || '';
      let pos = this.inputPosition
      val = type === 'func' ? `${val}()` : ` ${val}`;

      this.formData.expression = expression.slice(0,pos) + val + expression.slice(pos)
      this.inputPosition = this.inputPosition + (type === 'func' ? val.length -1 : val.length)
    },
    expChange(type, val) {
      if (val) {
        this.insertText(type, val)
        return
      }
    },
  },
  computed:{
    variableList() {
      let res = []
      // this.hierObject.hierProperties.content.forEach(item => {
      //   item.varName && (item.varName !== this.formData.varName )
      //     && res.push({label: item.varName, name: `${item.varName} `,value: item.varName})
      // })
      this.hierObject.web.data && this.hierObject.web.data.forEach(item => {
        item.properties && item.properties.varName && (item.properties.varName !== this.formData.varName )
          && res.push({label: item.properties.varName, value: item.properties.varName})
      })
      console.log("file: cfg-diagramModal.vue:147 variableList", this.hierObject.web.data, res,this.formData)
      return res
    },
    sourceList() {
      let res = []
      Object.keys(this.hierObject.sourceData).forEach(sKey => {
        let sItem = this.hierObject.sourceData[sKey]
        Object.keys(sItem).forEach(key => {
          res.push({label: `${sKey}.${key}`, value: `${sKey}.${key}`})
        })
      })
      return res
    },
    lang(){
      return {
        "en-US": {
          baseInfo: 'baseInfo',
          title:'node config',
          curWorkCenter:'current workCenter',
          workCenter:'workCenter',
          name: 'node name',
          varName: 'number',
          nodeTitleColor: 'node title color',
          nodeBgColor: 'node background color',
          type: 'type',
          className: 'class name',
          comments: 'comments',
          expression: 'expression',
          verify: 'verify',
          verifyResult: 'verify result',
          verifySuccess: 'verify success',
          calcFail: 'fail',
          source: 'source',
          verify: 'verify',
          variable: 'node variable',
          formula: 'formula',
          value: 'formula result',
        },
        "zh-CN": {
          baseInfo: '基本信息',
          title:'节点配置',
          curWorkCenter:'当前工作中心',
          workCenter:'工作中心',
          name: '节点名称',
          varName: '编号',
          nodeTitleColor: '节点标题颜色',
          nodeBgColor: '节点背景颜色',
          type: '所属类型',
          className: '模型类名',
          comments: '说明',
          expression: '表达式',
          verify: '验证',
          verifyResult: '验证结果',
          verifySuccess: '校验通过',
          calcFail: '失败',
          source: '数据源',
          verify: '验证',
          variable: '节点变量',
          formula: '公式',
          value: '计算结果',
        },
      }[this.G_Locale];
    }
  },
  mounted() {
  },
  watch: {
    'drawer.show'(val) {
    console.log("file: cfg-diagramModal.vue:227  val:", val,this.data)
      if (val) {
        this.formData = this.lodash.cloneDeep(this.data)
        this.calcMsg = {
          flag: true,
          content: []
        }
      }
    },
  },
  props:{
    drawer:{
      default:()=>{
        return {
          show: false
        };
      }
    },
    width:{
      default:()=>{
        return 600;
      }
    },
    hierObject:{
      default(){
        return {};
      }
    },
    data:{
      default:()=>{
        return {};
      }
    },
  },
}
</script>

<style lang="less" scoped>
  .colorTransferwp {
    width: 300px;
  }
  .btnwp {
    margin-top: 12px;
    .ivu-btn {
      margin-right: 12px;
    }
    .float-right {
      float: right;
    }
    .btnValidate {
      margin: 0;
    }
  }
</style>